import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ytx_plugin/x5_request.dart';

import '../../flutter_ytx_plugin.dart';

class X5WebView extends StatefulWidget {
  final Map<String, dynamic> map;
  final ValueChanged<Map<String, dynamic>>? listen;
  final ValueChanged<dynamic>? onPageStarted;
  final ValueChanged<dynamic>? onPageFinished;
  final ValueChanged<dynamic>? onProgressChanged;
  final ValueChanged<X5WebViewController>? onWebViewCreated;

  const X5WebView(
      {Key? key,
      required this.map,
      this.listen,
      this.onPageStarted,
      this.onPageFinished,
      this.onProgressChanged,
      this.onWebViewCreated})
      : super(key: key);

  @override
  _X5WebViewState createState() => _X5WebViewState();
}

class _X5WebViewState extends State<X5WebView> {
  X5Plugin x5Plugin = X5Plugin();

  @override
  void initState() {
    print("X5Sdk: ===========initState====:");
    x5Plugin.response.listen((event) {
      print("X5Sdk: ===========xxxx====:$event");
      if (event["key"] == "onPageStarted") {
        widget.onPageStarted?.call(event["value"]);
      } else if (event["key"] == "onPageFinished") {
        widget.onPageFinished?.call(event["value"]);
      } else if (event["key"] == "onProgressChanged") {
        widget.onProgressChanged?.call(event["value"]);
      }
      widget.listen?.call(event);
    });
    super.initState();
  }

  @override
  void dispose() {
    print("X5Sdk: ===========dispose====");
    x5Plugin.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (defaultTargetPlatform == TargetPlatform.android) {
      return PlatformViewLink(
        viewType: 'my_x5_platform_view',
        surfaceFactory:
            (BuildContext context, PlatformViewController controller) {
          return AndroidViewSurface(
            controller: controller as AndroidViewController,
            gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
              Factory<OneSequenceGestureRecognizer>(
                  () => TapGestureRecognizer()),
            },
            hitTestBehavior: PlatformViewHitTestBehavior.opaque,
          );
        },
        onCreatePlatformView: (PlatformViewCreationParams params) {
          return PlatformViewsService.initExpensiveAndroidView(
            id: params.id,
            viewType: 'my_x5_platform_view',
            layoutDirection: TextDirection.ltr,
            creationParams: widget.map,
            creationParamsCodec: const StandardMessageCodec(),
          )
            ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
            ..addOnPlatformViewCreatedListener((int id) {
              widget.onWebViewCreated?.call(X5WebViewController._(id, x5Plugin));
            })
            ..create();
        },
      );
    } else {
      return const Text("error");
    }
  }
}

class X5WebViewController {
  X5Plugin x5;

  X5WebViewController._(int id, this.x5);

  Future<void> loadUrl(String url, {Map<String, String>? headers}) async {
    x5.x5request.loadUrl(url, headers: headers);
  }

  Future<void> reload() async {
    x5.x5request.reload();
  }

  Future<void> canGoBack() async {
    x5.x5request.canGoBack();
  }

  Future<void> canGoForward() async {
    x5.x5request.canGoForward();
  }

  Future<void> goBack() async {
    x5.x5request.goBack();
  }

  Future<void> goForward() async {
    x5.x5request.goForward();
  }

  Future<void> goBackOrForward(int index) async {
    x5.x5request.goBackOrForward(index);
  }

  Future<void> currentUrl() async {
    x5.x5request.currentUrl();
  }

  Future<void> evaluateJavascript(Map<String, dynamic> map) async {
    x5.x5request.evaluateJavascript(map);
  }

  Future<void> addJavascriptChannels(Map<String, dynamic> map) async {
    x5.x5request.addJavascriptChannels(map);
  }
}
